<template>
  <el-form-item :prop="prop" :label="label" :rules="rulesList">
    <el-date-picker v-model="text" :placeholder="placeholder||placeholderText" :picker-options="pickerOptions" :value-format="valueFormat" v-bind="$attrs" v-on="$listeners" />
  </el-form-item>
</template>

<script>
const disabledBefore = {
  disabledDate(time) {
    return time.getTime() < Date.now() - 8.64e7
  }
}
const disabledAfter = {
  disabledDate(time) {
    return time.getTime() > Date.now()
  }
}

import fecha from '@/utils/external/date'
import { mixin } from './mixin'

export default {
  name: 'DatePicker',
  mixins: [mixin],
  model: {
    prop: 'value',
    event: 'changeModel'
  },
  props: {
    value: null,

    valueFormat: {
      type: String,
      default: 'yyyy-MM-dd'
    },

    disabledBefore: Boolean,
    disabledAfter: Boolean
  },
  data() {
    return {
      pickerOptions: null
    }
  },
  computed: {
    text: {
      get() {
        if (this.value) {
          if (this.valueFormat && this.valueFormat !== 'timestamp') {
            return fecha.format(new Date(this.value), this.valueFormat)
          }
          return this.value
        }
        return null
      },
      set(val) {
        this.$emit('changeModel', val)
      }
    }
  },
  created() {
    this.setDisabled()
  },
  methods: {
    setDisabled() {
      if (this.disabledBefore) {
        this.pickerOptions = disabledBefore
      } else if (this.disabledAfter) {
        this.pickerOptions = disabledAfter
      }
    }
  }
}
</script>
